const Item = require('../models/itemModel');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 配置文件上传
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'server/public/images/items/');
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, uniqueSuffix + path.extname(file.originalname));
    }
});

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 5 * 1024 * 1024, // 限制5MB
        files: 5 // 最多5张图片
    },
    fileFilter: function (req, file, cb) {
        // 只接受图片文件
        if (!file.originalname.match(/\.(jpg|jpeg|png|gif|svg)$/)) {
            return cb(new Error('只允许上传图片文件！'), false);
        }
        cb(null, true);
    }
});

// 获取所有物品
const getItems = async (req, res) => {
    try {
        const { tag, status, page = 1, limit = 10 } = req.query;
        const query = {};

        // 添加筛选条件
        if (tag) query.tags = tag;
        if (status) query.status = status;

        // 计算分页
        const skip = (page - 1) * limit;

        // 获取总数
        const total = await Item.countDocuments(query);

        // 获取物品列表
        const items = await Item.find(query)
            .populate('addedBy', 'username')
            .sort({ createdAt: -1 })
            .skip(skip)
            .limit(parseInt(limit));

        res.json({
            success: true,
            data: {
                items,
                pagination: {
                    total,
                    page: parseInt(page),
                    limit: parseInt(limit),
                    totalPages: Math.ceil(total / limit)
                }
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
};

// 获取单个物品详情
const getItemById = async (req, res) => {
    try {
        const item = await Item.findById(req.params.id)
            .populate('addedBy', 'username');

        if (!item) {
            return res.status(404).json({
                success: false,
                message: '物品不存在'
            });
        }

        res.json({
            success: true,
            data: {
                item
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
};

// 添加物品
const addItem = async (req, res) => {
    console.log("req.body:",req.body);
    try {
        if (!req.body.imageUrls || req.body.imageUrls.length === 0) {
            return res.status(400).json({
                success: false,
                message: '请上传至少一张物品图片'
            });
        }

        // 处理标签
        const tags = req.body.tags
        if (!Array.isArray(tags) || tags.length === 0) {
            return res.status(400).json({
                success: false,
                message: '请至少添加一个标签'
            });
        }

        // 处理图片URL
        const imageUrls = req.body.imageUrls.map(file => `/images/items/${file}`);

        const item = new Item({
            title: req.body.title,
            images: imageUrls,
            tags,
            status: req.body.status || '在库',
            location: req.body.location,
            description: req.body.description,
            addedBy: req.user._id
        });

        const newItem = await item.save();
        res.status(200).json({
            success: true,
            data: {
                item: newItem
            }
        });
    } catch (error) {
        res.status(400).json({
            success: false,
            message: error.message
        });
    }
};

// 搜索物品
const searchItems = async (req, res) => {
    try {
        const { query, tag, page = 1, limit = 10 } = req.query;
        const skip = (page - 1) * limit;

        // 构建搜索查询
        const searchQuery = {};
        if (query) {
            searchQuery.$text = { $search: query };
        }
        if (tag) {
            searchQuery.tags = tag;
        }

        // 获取总数
        const total = await Item.countDocuments(searchQuery);

        // 搜索物品
        const items = await Item.find(searchQuery)
            .populate('addedBy', 'username')
            .sort({ score: { $meta: "textScore" } })
            .skip(skip)
            .limit(parseInt(limit));

        res.json({
            success: true,
            data: {
                items,
                pagination: {
                    total,
                    page: parseInt(page),
                    limit: parseInt(limit),
                    totalPages: Math.ceil(total / limit)
                }
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
};

// 删除物品
const deleteItem = async (req, res) => {
    try {
        const item = await Item.findById(req.params.id);
        if (!item) {
            return res.status(404).json({
                success: false,
                message: '物品不存在'
            });
        }

        // 从文件系统中删除所有图片
        for (const imageUrl of item.imageUrls) {
            const imagePath = path.join(__dirname, '../public', imageUrl);
            if (fs.existsSync(imagePath)) {
                fs.unlinkSync(imagePath);
            }
        }

        // 从数据库中删除记录
        await item.deleteOne();
        res.json({
            success: true,
            data: {
                message: '物品已删除'
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
};

module.exports = {
    getItems,
    getItemById,
    addItem,
    searchItems,
    deleteItem,
    upload
}; 